package com.wz.utils.threadlocal;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author : Wang Zhen.
 * @Date : Created in 8:54 2022/12/2
 * @Description :
 * @Modified By   :
 * @Version :
 */
public class ThreadId {
    // Atomic integer containing the next thread ID to be assigned
    private static final AtomicInteger nextId = new AtomicInteger(0);

    // Thread local variable containing each thread's ID
    private static final ThreadLocal<Integer> threadId =
            new ThreadLocal<Integer>() {
                @Override protected Integer initialValue() {
                    return nextId.getAndIncrement();
                }
            };

    // Returns the current thread's unique ID, assigning it if necessary
    public static int get() {
        return threadId.get();
    }

    public static void main(String[] args) throws InterruptedException {
        RunnableTask task = new RunnableTask();
        Thread t1 = new Thread(task, "线程1");
        t1.start();
        TimeUnit.MILLISECONDS.sleep(100);

        Thread t2 = new Thread(task, "线程2");
        t2.start();
        TimeUnit.MILLISECONDS.sleep(100);

        Thread t3 = new Thread(task, "线程3");
        t3.start();
        TimeUnit.MILLISECONDS.sleep(100);
    }

    static class RunnableTask implements Runnable {

        @Override
        public void run() {
            try {
                System.out.println("当前线程名为： " + Thread.currentThread().getName() + ", 分配的线程ID为： " + threadId.get());
            } finally {
                threadId.remove();
            }
        }
    }
}
